package cn.luoyifan.mq._04_dierc;


import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/** 消费者
 * 1.创建连接
 * 2.创建通道
 * 3.创建队列
 * 4.绑定队列到交换机
 * 5.监听队列
 * 6.处理消息
 */
public class Consumer1 {
        public final static String NAME_DIERC_LUOYIFAN1 = "NAME_DIERC_LUOYIFAN1";


        public static void main(String[] args) throws IOException, TimeoutException {
            //1.创建连接
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("115.159.88.63");
            Connection connection = factory.newConnection();
            //2.创建通道
            Channel channel = connection.createChannel();

            //* 3.创建队列
            channel.queueDeclare(NAME_DIERC_LUOYIFAN1,true,false,false,null);

            //* 4.绑定队列到交换机
            channel.queueBind(NAME_DIERC_LUOYIFAN1,Producer.QUEUE_DIERC_LUOYIFAN,"error");
            channel.queueBind(NAME_DIERC_LUOYIFAN1,Producer.QUEUE_DIERC_LUOYIFAN,"info");

            //4.处理消息
            //消息的处理回调
            Consumer callback = new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    System.out.println("拿到消息："+ new String(body));
                    System.out.println("consumerTag = "+consumerTag);
                    System.out.println("交换机 = "+envelope.getExchange());
                    System.out.println("队列 = " +envelope.getRoutingKey());
                    System.out.println("消息的ID = "+envelope.getDeliveryTag());
                }
            };

            //3.监听队列
            channel.basicConsume(NAME_DIERC_LUOYIFAN1,false,callback);
    }

}
